const {
  validate
} = require('../../../../utils/util');

const { requestSubscribeMessage } = require('../../../../api/index');

const { friendshipActivityApply } = require('../../../../api/fraternity');

const {
  education_access
} = require('../../../../utils/config');

//  缓存 this
let that = null;
// pages/authentication/index/index.js
Page({

  /*** 页面的初始数据 */
  data: {
    formData: {
      friendshipAssociationId: '', // 联谊会ID
      title: '',  // 活动标题
      applyStudentId: wx.getStorageSync('studentid'), // 申请人 id
      introduction: '', //  介绍，描述
      location: '',  //活动地点
      registrationBeginTime: '',
      registrationEndTime: '',
      activityBeginTime: '',
      activityEndTime: '',
      activityPhoto: '',
      activityFee: '', // 申请资金说明 - 活动费用
      contactName: '', // 联系人
      contactPhone: '', //  联系方式
      applyFundReason: '', // 资金申请说明
      applyReason: ''   // 申请理由
    },
    fileList: [],
    errors: {},
    rules: {
      title: [{
        empty: true,
        msg: '活动标题不能为空'
      }],
      registrationBeginTime: [{
        empty: true,
        msg: '报名开始时间不能为空'
      }],
      registrationEndTime: [{
        empty: true,
        msg: '报名结束时间不能为空'
      }, {
        rule: val => {
          const { registrationBeginTime, registrationEndTime } = that.data.formData;
          const num = new Date(registrationEndTime) - new Date(registrationBeginTime);
          if( isNaN(num) || num > 0) {
            return true;
          }
        },
        msg: '活动结束时间不能小于开始时间'
      }],
      activityBeginTime: [{
        empty: true,
        msg: '活动开始时间不能为空'
      }, {
        rule: val => {
          const { activityBeginTime, registrationEndTime } = that.data.formData;
          const num = new Date(activityBeginTime) - new Date(registrationEndTime);
          if( isNaN(num) || num > 0) {
            return true;
          }
        },
        msg: '活动开始时间必须在报名结束时间之后'
      }],
      activityEndTime: [{
        empty: true,
        msg: '活动结束时间不能为空'
      }, {
        rule: val => {
          const { activityBeginTime, activityEndTime } = that.data.formData;
          const num = new Date(activityEndTime) - new Date(activityBeginTime);
          if( isNaN(num) || num > 0) {
            return true;
          }
        },
        msg: '活动结束时间不能小于开始时间'
      }],
      activityFee: [{
        empty: true,
        msg: '活动费用不能为空'
      }],
      location: [{
        empty: true,
        msg: '活动地点不能为空'
      }],
      contactName: [{
        empty: true,
        msg: '联系人不能为空'
      }],
      introduction: [
        {
          empty: true,
          msg: '请输入活动详情：活动流程、注意事项等（必填）'
        }
      ],
      contactPhone: [
        {
          empty: true,
          msg: '联系方式不能为空'
        },
        {
          rule: val => /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(val),
          msg: '手机号码格式有误'
        }
      ],
      activityPhoto: [{
        empty: true,
        msg: '活动主图不能为空'
      }],
      applyFundReason: [
        {
          empty: true,
          msg: '申请资金说明不能为空'
        }
      ],
      applyReason: [{
        empty: true,
        msg: '为了便于审核，请详细描述您的申请理由（必填）'
      }]
    }
  },
  //  页面跳转
  onJump( event ) {
    const { url } = event.currentTarget.dataset;
    wx.navigateTo({ url });
  },
  //  修改表单数据
  onFormData(event) {
    const { prop } = event.currentTarget.dataset;
    this.data.formData[prop] = event.detail;
  },
  // 提交数据
  async onSubmit(event) {
    // requestSubscribeMessage('tx9vXyJaBT87kzBgjg4zik63EXh1W-n5AJichF-ilTk');

    //  判断返回的错误集合是否是空的，如果空则说明验证通过了，否则将错误显示到页面上
    const errors = validate(this.data.formData, this.data.rules);

    if ( errors ) { //  如果报错就不允许进行数据的提交
      this.setData({ errors });
      return;
    }

    fetchFriendshipActivityApply.call(this);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    that = this;
    this.data.formData.friendshipAssociationId = options.id;
  },
})

//  发送请求
async function fetchFriendshipActivityApply() {
  const _data = setResult.call(this, this.data.formData);
  const { errors = [], result } = await friendshipActivityApply(_data);

  if(errors.length > 0) { return; }

    //  授权成功 之后调整页面
    const res = await requestSubscribeMessage([education_access]);

    if (res[education_access] = "accept") {
      wx.showToast({
        title: '订阅成功',
        icon: 'success',
        duration: 1000,
        success() {
          wx.navigateTo({ url: `/packageA/pages/success/index?type=active_apply` });
        }
      })
    } else { //  提示未通过
      //  填写完成之后 返回到上一页
      wx.navigateTo({ url: `/packageA/pages/success/index?type=active_apply` });
    }
}

function setResult(data) {
  const _data = JSON.parse(JSON.stringify(data));

  return _data;
}